﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Solution18
    {
        public IList<int> SpiralOrder(int[][] matrix)
        {
            List<int> list = new List<int>();
            if (matrix == null || matrix.Length == 0)
            {
                return list;
            }
            int rowNum = matrix.Length;
            int colNum = matrix[0].Length;
            int left = 0;
            int right = colNum - 1;
            int top = 0;
            int bottom = rowNum - 1;
            while (list.Count() < rowNum * colNum)
            {
                for (int col = left; col <= right; col++)
                {
                    list.Add(matrix[top][col]);
                }
                top++;
                if (list.Count() < rowNum * colNum)
                {
                    for (int row = top; row <= bottom; row++)
                    {
                        list.Add(matrix[row][right]);
                    }
                    right--;
                }
                if (list.Count() < rowNum * colNum)
                {
                    for (int col = right; col >= left; col--)
                    {
                        list.Add(matrix[bottom][col]);
                    }
                    bottom--;
                }
                if (list.Count()<rowNum*colNum)
                {
                    for (int row = bottom; row >=top; row--)
                    {
                        list.Add(matrix[row][left]);
                    }
                    left++;
                }
            }
            return list;
        }
    }
}
